package com.myCinema.copy;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ActionServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String url = request.getRequestURI();
		String contextUrl = request.getContextPath();
		String name = url.substring(contextUrl.length()+1, url.indexOf(".action"));
		ActionMapping am = ActionMapper.createActionMapping(name);
		try {
			Class clz = Class.forName(am.getClassName());
			Action action = (Action) clz.newInstance();
			String result = action.execute(request, response);
			Result r = am.getMapping().get(result);
			if("redirect".equals(r.getType()))
				response.sendRedirect(r.getUrl());
			else if("dispatcher".equals(r.getType()))
				request.getRequestDispatcher(r.getUrl()).forward(request, response);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
